/*************************************************************************
 *
 * funkce pro hi-level pristup k vstupum/vystupum
 * 
 * (c) Ales Povalac, alpov@alpov.net, http://www.alpov.net/
 * 
 *************************************************************************
 *
 * $Id: io.c 128 2007-02-18 20:35:06Z alpov $
 * 
 *************************************************************************/         

#include <stdint.h>
#include <avr/io.h>
#include "../avrx/avrx.h"
#include "../avrx/AvrXFifo.h"
#include "io.h"


/*************************************************************************
 * inicializace
 *************************************************************************/ 
void InitIo(void)
{
    PORTD |= _BV(PD3);
    DDRA |= _BV(PA4) | _BV(PA5) | _BV(PA6) | _BV(PA7);
}


/*************************************************************************
 * cteni optovstupu
 *************************************************************************/ 
signed char ReadInput(unsigned char id)
{
    unsigned char i, j = 0;
    TimerControlBlock timer;
    
    if (id > 0)
        return -1;
    
    timer.semaphore = SEM_PEND;
    for (i = 0; i < 10; i++) {
        if (bit_is_set(PIND, PD3))
            j++;
        
        AvrXDelay(&timer, 2);
    }
    
    return (j > 8) ? 0 : 1;
}


/*************************************************************************
 * zapis vystupu - sepnuti rele
 *************************************************************************/ 
signed char SetOutput(unsigned char id)
{
    if (id > 3)
        return -1;
    
    switch (id) {
        case 0: PORTA |= _BV(PA4); break;
        case 1: PORTA |= _BV(PA5); break;
        case 2: PORTA |= _BV(PA6); break;
        case 3: PORTA |= _BV(PA7); break;
    }

    return 1;
}


/*************************************************************************
 * zapis vystupu - rozepnuti rele
 *************************************************************************/ 
signed char ClearOutput(unsigned char id)
{
    if (id > 3)
        return -1;
    
    switch (id) {
        case 0: PORTA &= ~_BV(PA4); break;
        case 1: PORTA &= ~_BV(PA5); break;
        case 2: PORTA &= ~_BV(PA6); break;
        case 3: PORTA &= ~_BV(PA7); break;
    }

    return 1;
}

